package com.exam.aspect;

import com.exam.common.ServResult;
import com.exam.common.SnowflakeId;
import com.exam.service.TLogService;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
public class LogAspect {

    @Autowired
    private TLogService tLogService;
    // id
    SnowflakeId snowflakeId = new SnowflakeId(10, 10);

    private final static Logger logger = LoggerFactory.getLogger(LogAspect.class);

    // ..表示包及子包 该方法代表controller层的所有方法
    @Pointcut("execution(public * com.exam.controller..*.*(..))")
    public void controllerMethod() {
    }

    @Before("controllerMethod()")
    public void LogRequestInfo(JoinPoint joinPoint) throws Exception {

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Map<String, Object> map = new HashMap<>();
        map.put("id", snowflakeId.nextStrId());
        map.put("logNo", "");
        map.put("menuNo","");
        map.put("url", request.getRequestURI());
        map.put("userNo","");
        map.put("userName", "");
        map.put("ip", request.getRemoteHost());
        map.put("className", joinPoint.getSignature().getDeclaringTypeName());
        map.put("httpMethod", request.getMethod());
        map.put("methodName", joinPoint.getSignature().getName());
        map.put("args", "");
        tLogService.save(map);

    }

    // 判断是否查询成功
    @AfterReturning(returning = "servResult", pointcut = "controllerMethod()")
    public void logResultVOInfo(ServResult servResult) throws Exception {
        logger.info("请求结果：" + servResult.getCode() + "\t" + servResult.getMsg());
    }

}
